package com.ruoyi.project.system.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.Record;
import com.ruoyi.project.system.domain.SysPayOrder;
import com.ruoyi.project.system.domain.SysQuery;
import com.ruoyi.project.system.domain.SysTax;
import com.ruoyi.project.system.mapper.SysQueryMapper;
import com.ruoyi.project.system.service.ISysPayOrderService;
import com.ruoyi.project.system.service.ISysQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import static com.ruoyi.common.utils.DateUtils.parseDateToStr;

/**
 * 进件记录Controller
 */
@RestController
@RequestMapping("/query")
public class SysQueryController extends BaseController {

    @Autowired
    private ISysQueryService sysQueryService;

    @Autowired
    private ISysPayOrderService iSysPayOrderService;

    @Autowired
    private SysQueryMapper sysQueryMapper;

    @Autowired
    private RedisCache redisCache;

    @GetMapping("/shield/{id}")
    public AjaxResult shield(@PathVariable("id") Long queryId) {
        if (queryId == null) {
            return error("没有单号！");
        }
        SysQuery sysQuery = sysQueryService.selectSysQueryById(queryId);
        if (sysQuery == null && StringUtils.isEmpty(sysQuery.getQueryInfo())) {
            return error("无数据！");
        }
        JSONObject info = JSON.parseObject(sysQuery.getQueryInfo());
        if (sysQuery.getProductId() == 2) {
            info.getJSONObject("dttz").getJSONObject("retdata").getJSONObject("Flag").replace("executionlimited", 0);
//            info.getJSONObject("dttz").getJSONObject("retdata").remove("ExecutionLimited");
        } else {
            info.getJSONObject("grss").getJSONObject("retdata").replace("resultCode", 0);
//            info.getJSONObject("grss").getJSONObject("retdata").remove("detail");
        }
        return toAjax(sysQueryService.updateSysQuery(new SysQuery(queryId, info.toJSONString())));
    }

    /**
     * 即时查询项目
     */
    @GetMapping("/data")
    public AjaxResult query(String name, String orderNo) {
        if (StringUtils.isEmpty(orderNo)) {
            return error("没有单号！");
        }
        SysPayOrder payOrder = iSysPayOrderService.selectSysPayOrderByOrderNo(orderNo);
        if (payOrder == null) {
            return warn("不存在支付订单");
        } else if (!"SUCCESS".equals(payOrder.getPayState())) {
            return warn("订单未支付");
        } else if (!payOrder.getBody().equals(name)) {
            return warn("与查询类型不符");
        }
        SysQuery sysQuery = sysQueryService.selectSysQueryById( Long.parseLong(payOrder.getOutId()));
        if (sysQuery != null && StringUtils.isNotEmpty(sysQuery.getQueryInfo())) {
            sysQuery.setUpdateTime(DateUtils.getNowDate());
        } else {
            AjaxResult query;
            if (sysQuery.getProductId() == 1) {
                query = sysQueryService.bigDataQueryPro(sysQuery);
            } else if (sysQuery.getProductId() == 2) {
                query = sysQueryService.bigDataQuery(sysQuery);
            } else if (sysQuery.getProductId() == 4) {
                query = sysQueryService.marryQuery(sysQuery, orderNo);
            } else if (sysQuery.getProductId() == 5) {
                query = sysQueryService.judicialQuery(sysQuery);
            } else {
                return error("没有此产品编号！");
            }
            for (String key : query.keySet()) {
                JSONObject value = (JSONObject) query.get(key);
                if (value.get("retdata") instanceof String) {
                    if (!"000000".equals(value.getString("retcode"))) {
                        return error("数据出错！");
                    }
                    String retdata = value.getString("retdata");
                    if ('[' == retdata.charAt(0)) {
                        value.replace("retdata", JSON.parseArray(retdata));
                    } else if ('{' == retdata.charAt(0)) {
                        value.replace("retdata", JSON.parseObject(retdata));
                    }
                    query.replace(key, value);
                }
            }
            String queryInfo = JSON.toJSONString(query);
            sysQueryService.updateSysQuery(new SysQuery(sysQuery.getId(), queryInfo));
            sysQuery.setQueryInfo(queryInfo);
        }
        if (StringUtils.isNotEmpty(sysQuery.getName())) {
            sysQuery.setName("**" + sysQuery.getName().substring(1));
        }
        if (StringUtils.isNotEmpty(sysQuery.getCardNo())) {
            sysQuery.setCardNo("******" + sysQuery.getCardNo().substring(6));
        }
        if (StringUtils.isNotEmpty(sysQuery.getMobile())) {
            sysQuery.setMobile("*******" + sysQuery.getMobile().substring(7));
        }
        return success(sysQuery);
    }

    /**
     * 新增企业查询
     */
    @Anonymous
    @PostMapping("/addPayTaxesQuery")
    public AjaxResult addPayTaxesQuery(@RequestBody SysQuery sysQuery) {
        // 检查参数
        if (StringUtils.isEmpty(sysQuery.getMobile()) || sysQuery.getUserId() == null) {
            return error("缺少参数！");
        }
        // 初级写入
        sysQueryService.insertSysQuery(sysQuery);
        // 发送请求
        JSONObject qyns = sysQueryService.companyQuery(sysQuery);
        if (!"000000".equals(qyns.getString("retcode"))) {
            return error(qyns.getString("retmsg"));
        }
        // 写入具体数据
        SysTax tax = new SysTax(sysQuery.getId().intValue(), qyns.toJSONString());
        sysQueryMapper.insertSysTax(tax);
        // 整理数据
        sysQuery.setQueryInfo(tax.getId().toString());
        sysQueryService.updateSysQuery(sysQuery);

        sysQuery.setQueryInfo(qyns.getJSONObject("retdata").toJSONString());
        return success(sysQuery.getId());
    }

    /**
     * 获取纳税查询采集页面
     */
    @Anonymous
    @GetMapping("/getPayTaxesAuthUrl/{id}")
    public AjaxResult getPayTaxesAuthUrl(@PathVariable("id") @NotNull(message = "没有单号") Long id) {
        HashMap<String, String> tax = sysQueryMapper.selectSysTaxByQueryId(id);
        if (tax == null || tax.isEmpty()) {
            return error("不存在的订单");
        }
        return success(tax);
    }

    /**
     * 获取企业纳税收集结果
     */
    @Anonymous
    @GetMapping("/getPayTaxes/{id}")
    public AjaxResult getPayTaxes(@PathVariable("id") @NotNull(message = "没有单号") Long id) {

        HashMap<String, String> taxMap = sysQueryMapper.selectSysTaxByQueryId(id);

        JSONObject taxAuthUrl = JSON.parseObject(taxMap.get("taxAuthUrl"));
        String taskId = taxAuthUrl.getJSONObject("retdata").getString("taskId");

        String responseStr = HttpUtils.sendGet("http://175.178.170.139:8089/jiekou/qtrs?taskId=" + taskId);

        sysQueryMapper.updateQueryTaxReportStatusOfTax(id, responseStr);
        return success(responseStr);
    }

    /**
     * 查询企业纳税
     */
    @Anonymous
    @GetMapping("/getPayTaxesData")
    public AjaxResult getPayTaxesData(String name, @NotBlank(message = "没有单号！") String orderNo) {
        SysPayOrder sysQueryPay = iSysPayOrderService.selectSysPayOrderByOrderNo(orderNo);
        if (sysQueryPay == null) {
            return error("不存在的支付订单");
        } else if (!"SUCCESS".equals(sysQueryPay.getPayState())) {
            return error("订单未支付");
        } else if (!sysQueryPay.getBody().equals(name)) {
            return error("与查询项目不符");
        }

        Long id = Long.parseLong(sysQueryPay.getOutId());
        HashMap<String, String> taxMap = sysQueryMapper.selectSysTaxByQueryId(id);

        if (taxMap.isEmpty() || StringUtils.isEmpty(taxMap.get("queryTaxReport"))) {
            String requestSn = JSON.parseObject(taxMap.get("taxAuthUrl")).getString("request_sn");

            String returnStr = HttpUtils.sendGet("http://175.178.170.139:8089/jiekou/comInfo?requestSn=" + requestSn);

            sysQueryMapper.updateQueryTaxReportOfTax(id, returnStr);

            if (StringUtils.isNotEmpty(returnStr) && JSON.parseObject(returnStr).getInteger("code") != 200) {
                return error("数据异常");
            }
            return success(JSON.parseObject(returnStr));
        } else {
            return success(JSON.parseObject(taxMap.get("queryTaxReport")));
        }
    }

    /**
     * 查询个人不动产
     */
//    @Anonymous
//    @GetMapping("/immData")
//    public AjaxResult immData(String orderNo) {
//        return sysQueryService.immovablePropert(sysQueryMapper.getQueryByOrderNo(orderNo));
//    }

    @Anonymous
    @GetMapping("/concealKeyword/{orderNo}")
    public AjaxResult concealKey(@PathVariable("orderNo") String orderNo) {
        AjaxResult result = new AjaxResult();
        SysQuery sysQuery = sysQueryMapper.getQueryByOrderNo(orderNo);

        result.put("createTime", parseDateToStr("yyyy-MM-dd HH:mm:ss", sysQuery.getCreateTime()) );
        result.put("userId", sysQuery.getUserId());

        if (StringUtils.isNotEmpty(sysQuery.getName())) {
            result.put("name", "**" + sysQuery.getName().substring(1));
        }
        if (StringUtils.isNotEmpty(sysQuery.getCardNo())) {
            result.put("cardNo", "******" + sysQuery.getCardNo().substring(6));
        }
        if (StringUtils.isNotEmpty(sysQuery.getMobile())) {
            result.put("mobile", "*******" + sysQuery.getMobile().substring(7));
        }
        if (StringUtils.isNotEmpty(sysQuery.getMoreKeyword())) {
            String moreKeyword = sysQuery.getMoreKeyword();
            result.put("moreKeyword", "****" + (moreKeyword.length() < 8 ? moreKeyword : moreKeyword.substring(8)));
        }
        return result;
    }


    /**
     * 获取进件记录详细信息
     */
    @Anonymous
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        SysQuery sysQuery = sysQueryService.selectSysQueryById(id);
        return success(sysQuery);
    }

    /**
     * 新增进件记录
     */
    @Anonymous
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SysQuery sysQuery) {
        sysQueryService.insertSysQuery(sysQuery);
        return success(sysQuery.getId());
    }


    /**
     * 查询进件记录列表
     */
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(SysQuery sysQuery) {
        startPage();
        List<SysQuery> list = sysQueryService.selectSysQueryList(sysQuery);
        return getDataTable(list);
    }

    /**
     * 查询进件记录列表
     */
    @Anonymous
    @GetMapping("/recordList")
    public List<Record> recordList(String mobile, String sign) {
        // 拉取数据
        return sysQueryService.getRecords(mobile, sign);
    }

    /**
     * 查询进件记录列表通过手机号
     */
    @Anonymous
    @GetMapping("/recordListByMobile")
    public AjaxResult recordListByMobile(String mobile, String code) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + mobile;
        String captcha = redisCache.getCacheObject(verifyKey);
        if (StringUtils.isEmpty(captcha)) {
            return AjaxResult.error(4002, "验证码失效");
        }
        redisCache.deleteObject(verifyKey);
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(code, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 拉取数据
        return AjaxResult.success(sysQueryService.getRecords(mobile, null));
    }

    /**
     * 导出进件记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:query:export')")
    @Log(title = "进件记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysQuery sysQuery) {
        List<SysQuery> list = sysQueryService.selectSysQueryList(sysQuery);
        ExcelUtil<SysQuery> util = new ExcelUtil<SysQuery>(SysQuery.class);
        util.exportExcel(response, list, "进件记录数据");
    }

    /**
     * 修改进件记录
     */
    @PutMapping
    @Anonymous
    public AjaxResult edit(@RequestBody SysQuery sysQuery) {
        return toAjax(sysQueryService.updateSysQuery(sysQuery));
    }

}
